package com.travelsky.airchina.boarding.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

 /**
  * 日期处理的类
  * Nov 17, 2005 4:47:54 PM
  */
public final class DateUtil {
    /**
     * 日期格式化对象
     */
    private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    
    private static DateFormat dateFormat_input = new SimpleDateFormat("yyyyMMdd");
    /**
     * 日期时间格式化对象
     */
    private static DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    private static DateFormat nowdateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
    
    private static DateFormat dateTimeFormat_input = new SimpleDateFormat("yyyyMMddHHmm");
    /**
     * 时间格式化对象
     */
    private static DateFormat timeFormat = new SimpleDateFormat("HH:mm");
    
    private static DateFormat hourFormat = new SimpleDateFormat("HH");
    
    /**
     * 用于重点生产资料监测系统
     */
    private static final int day = 1;
    /**
     * 用于重点生产资料监测系统
     */
    private static final int lastDay = 15;
    
    public static int getDay() {
		return day;
	}
	public static int getLastDay() {
		return lastDay;
	}
	
	
	public static Date parsDate(String date ){
		DateFormat df = new SimpleDateFormat("yyyyMMdd");
		Date retDate = null;
		try {
			retDate = df.parse(date);
		} catch (ParseException e) {
		}
		return retDate;
	}
	
	/**
	 * 得到星期几
	 * 星期一,二,三,四,五,六,日分别
	 * 对应1, 2,3, 4,5, 6,0
	 * @param date
	 * @return
	 */
	public static int getWeekDay(String date) {
		//GregorianCalendar gc = new GregorianCalendar();
		Calendar calendar = Calendar.getInstance();
		
		calendar.setTime(parsDate(date)); // 设置为指定日期
		int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)-1 ;// 星期几
		return dayOfWeek;
	}
	
	public static String convert(int val){ 
		String retStr = ""; 
		switch (val) { 
		case 0: 
		return "星期日"; 
		case 7: 
		return "星期日"; 
		case 1: 
		return "星期一"; 
		case 2: 
		return "星期二"; 
		case 3: 
		return "星期三"; 
		case 4: 
		return "星期四"; 
		case 5: 
		return "星期五"; 
		case 6: 
		return "星期六"; 
		default: 
		break; 
		} 
		return retStr; 
	}
	
	public  static String parse(String arg) {
		if(arg!=null&&!arg.equals("")) {
			String [] date = arg.split("月");
			String year = new SimpleDateFormat("yyyy").format(new Date());
			String month = date[0];
			if(month.length()==1) {
				month = "0" + month;
			}
			
			String day = date[1].split("日")[0];
			if(day.length()==1) {
				day = "0"+day;
			}
			return year+month+day;
		}else {
			return new SimpleDateFormat("yyyyMMdd").format(new Date());
		}
		
	}
	
	
	public static String getMonthFirstDay(Date date){
		if(date ==null){
			date = new Date();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		return sdf.format(date)+"01";
		
	}
	
	public static String getYearFirstMonth(Date date){
		if(date == null){
			date = new Date();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		return sdf.format(new Date())+"01";
	}
	
	public static String getTodayMonth(Date date){
		if(date == null){
			date = new Date();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		return sdf.format(date);
	}
	
	
	public static String getStringDate(Date date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return sdf.format(date);
	}
	
	
	/**
     * 获取时间格式化对象 "yyyy-MM-dd"
     * @return
     */
    public static final DateFormat getDateFormat(){
        return dateFormat;
    }
    /**
     * 日期输入格式采用"yyyyMMdd"
     * @return
     */
    public static final DateFormat getDateFormat_input(){
        return dateFormat_input;
    }
    
    /**
     * 获取时间日期格式化对象 "yyyy-MM-dd HH:mm:ss"
     * @return
     */
    public static final DateFormat getDateTimeFormat(){
        return dateTimeFormat;
    }
    
    /**
     * 获取当前时间的时间对象
     * @return
     */
    public static final Date nowDate(){
        return new Date();
    }
    /**
     * 系统最小时间
     * @return
     */
    public static final Date minDate() {
        return dateBegin(getDate(1900,1,1));
    }
    /**
     * 系统最大时间
     * @return
     */
    public static final Date maxDate() {
        return dateEnd(getDate(2079,1,1));
    }
    /**
     * 获取指定时间的年
     * @param date
     * @return
     */
    public static final int year(Date date){
    	if(date==null)return 0;
    	
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }
    /**
     * 获取指定时间的月
     * @param date
     * @return
     */
    public static final int month(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH)+1;
    }
    /**
     * 获取指定时间的日
     * @param date
     * @return
     */
    public static final int day(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DATE);
    }
    /**
     * 获取一个时间对象
     * @param year 格式为：2004
     * @param month 从1开始
     * @param date 从1开始
     * @return
     */
    public static final Date getDate(int year,int month,int date){
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month-1, date);
        return calendar.getTime();        
    }
    
    /**
     * 获取一个时间对象
     * @param year 格式为：2004
     * @param month 从1开始
     * @param date 从1开始
     * @param hour
     * @param minute
     * @param second
     * @return
     */
    public static final Date getDateTime(int year, int month, int date, int hour, int minute,
            int second){
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month-1, date,hour,minute,second);
        return calendar.getTime();        
    }
    
    /**
     * 在一个已知时间的基础上增加指定的时间
     * @param oleDate
     * @param year
     * @param month
     * @param date
     * @return
     */
    public static final Date addDate(Date oldDate, int year, int month, int date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(oldDate);
        calendar.add(Calendar.YEAR, year);
        calendar.add(Calendar.MONTH, month);
        calendar.add(Calendar.DATE, date);        
        return calendar.getTime();        
    }
    
    public static int constDateSub=-36500;
    /**
     * 返回两个时间相差的天数
     * @param a
     * @param b
     * @return
     */
    public static final int dateSub(Date a,Date b) {
    	if (a==null||b==null) {
			return constDateSub;
		}
    	
    	
        int date = (int)(a.getTime()/(24*60*60*1000) - b.getTime()/(24*60*60*1000));
        return  date;
    }
    
    public static final int dateSubAddOne(Date a,Date b) {
        int date = (int)(a.getTime()/(24*60*60*1000) - b.getTime()/(24*60*60*1000));
        return date<=0?1:date+1;
    }
    
    public static final boolean isBetweenDateS(Date beginDate,Date nowDate,Date endDate){
    	if(beginDate!=null&&nowDate!=null&&endDate!=null){
    		if((beginDate.getTime()/(24*60*60*1000))<=(nowDate.getTime()/(24*60*60*1000))&&(nowDate.getTime()/(24*60*60*1000))<=(endDate.getTime()/(24*60*60*1000))){
    			return true;
    		}
    	}else	
    	if(beginDate!=null&&nowDate!=null&&endDate==null){
    		if((beginDate.getTime()/(24*60*60*1000))<=(nowDate.getTime()/(24*60*60*1000))){
    			return true;
    		}
    	}else
    	if(beginDate==null&&nowDate!=null&&endDate!=null){
    		if((nowDate.getTime()/(24*60*60*1000))<=(endDate.getTime()/(24*60*60*1000))){
    			return true;
    		}
    	}
    	return false;
    }
    
    /**
     * 返回两个时间相差多少分钟
     * @param a
     * @param b
     * @return
     */
    public static final int subSecond(Date a,Date b) {
        return (int)(a.getTime()/(1000) - b.getTime()/(1000));
    }
    public static final int subSecond(String str,Date b){
        Date a = null;
        try {
            a = timeFormat.parse(str);
        } catch (ParseException e) {
           
            return 0; 
        }
        return (int)((a.getTime()%(24*60*60*1000))/1000-(b.getTime()%(24*60*60*1000))/1000);
    }
    /**
     * 一天的开始时间
     * @param date
     * @return
     */
    public static final Date dateBegin(Date date) {
        if(date == null)
            return null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        dateBegin(calendar);
        return calendar.getTime();
    }
    /**
     * 一天的结束时间
     * @param date
     * @return
     */
    public static final Date dateEnd(Date date) {
        if(date == null)
            return null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        dateEnd(calendar);
        return calendar.getTime();
    }
    /**
     * 一天的结束时间
     * @param calendar
     * @return
     */
    public static final Calendar dateEnd(Calendar calendar) {
        if(calendar == null)
            return null;
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar;
    }
    /**
     * 一天的开始时间
     * @param calendar
     * @return
     */
    public static final Calendar dateBegin(Calendar calendar) {
        if(calendar == null)
            return null;
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar;
    }
    /**
     * 一月的开始时间
     * @param date
     * @return
     */
    public static final Date monthBegin(Date date) {
        if(date == null)
            return null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int day = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DATE, day);
        dateBegin(calendar);
        return calendar.getTime();
    }
    /**
     * 一月的技术时间
     * @param date
     * @return
     */
    public static final Date monthEnd(Date date) {
        if(date == null)
            return null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DATE, day);
        dateEnd(calendar);
        return calendar.getTime();
    }
    /**
     * 一年的开始时间
     * @param date
     * @return
     */
    public static final Date yearBegin(Date date) {
        if(date == null)
            return null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int month = calendar.getActualMinimum(Calendar.DAY_OF_YEAR);
        calendar.set(Calendar.DATE, month);
        dateBegin(calendar);
        return calendar.getTime();
    	//return  parseDate(formatDate(date).substring(0,4)+"-01-01");
    }
    /**
     * 一年的结束时间
     * @param date
     * @return
     */
    public static final Date yearEnd(Date date) {
        if(date == null)
            return null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int day = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
        calendar.set(Calendar.DATE, day);
        dateEnd(calendar);
        return calendar.getTime();
    	//return  parseDate(formatDate(date).substring(0,4)+"-12-31");
    }
    /**
     * 从字符串转换为date
     * 默认格式为 "yyyy-MM-dd"
     * @param source
     * @return
     */
    public static final Date parseDate(String source){ 
        if(source==null || source.trim().length()==0)
            return null;
        if(source.trim().length()==8)
        try {
			Date returnDate = dateFormat_input.parse(source); 
            return returnDate;
        } catch (ParseException e) {
			//logger.error("DateUtil parseDate error", e);  
            return null;
        }
         
        try {
			Date returnDate = dateFormat.parse(source); 
            return returnDate;
        } catch (ParseException e) {
			//logger.error("DateUtil parseDate error", e);  
            return null;
        }
    }
    
    /**
     * 从字符串转换为date
     * 默认格式为 "yyyy-MM-dd HH:mm:ss"
     * @param source
     * @return
     */
    public static final Date parseDateTime(String source){
        if(source==null || source.length()==0)
            return null;
        try {
            return dateTimeFormat.parse(source);
        } catch (ParseException e) {
        	//logger.error("DateUtil parseDate error", e); 
            return null;
        }
    }
    /**
     * 格式化输出（只读的时候）
     * 默认格式为 "yyyy-MM-dd"
     * @param date
     * @return
     */
    public static String formatDate(Date date){
        if(date == null)return "";
        return dateFormat.format(date);
    }
    
    public static String dataTimeDate(Date date){
        if(date == null)return "";
        return dateTimeFormat.format(date);
    }
    /**
     * 格式化输出显示（填写的时候） yyyyMMdd
     * @param date
     * @return
     */
    public static String formatDate_input(Date date){
        if(date == null)return "";
        return dateFormat_input.format(date);
    }
    
    /**
     * 格式化输出
     * 默认格式为 "yyyy-MM-dd HH:mm"
     * @param date
     * @return
     */
    public static String formatDateTime(Date date){
        if(date == null)return "";
        return dateTimeFormat.format(date);
    }
    
    /**
     * 格式化输出
     * 默认格式为 "yyyy-MM-dd HH:mm:ss"
     * @param date
     * @return
     */
    public static String getNowDateTime(){
        return nowdateTime.format(DateUtil.nowDate());
    }
    
    public static String formatDateTime_input(Date date){
        if(date == null)return "";
        return dateTimeFormat_input.format(date);
    }
    
    //获得小时数
    public static String formatDateHour(Date date){
    	if(date == null){
    		date = new Date();
    	}
    	return hourFormat.format(date);
    }
    
    
    
    /**
     * 判断是否是闰年
     * @param yearInt
     * @return
     */
    public static boolean isLeapYear(int yearInt){
    	boolean flag = false;
		if(((yearInt%4==0)&&(yearInt%100!=0))||((yearInt%4==0)&&(yearInt%400==0))){
			return true;
		}
    	return flag;
    }
	/**
	 * 
	 * @param days
	 * @return
	 */
	public static Date addDays(Date date,int days){
		Date newdate=new Date();
		long newtimems=date.getTime()+(days*24*60*60*1000);
		newdate.setTime(newtimems);
		return newdate;
	}
	
	
	public static String getToday(Date date)
	{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return sdf.format(date);
	}
	
	
    /**
     * 判断8位的日期的字符串是否为正确的日期字符串
     * @param dateString
     * @return 不是正确的日期字符串返回true
     */
    public static boolean isErrorFormatDateString(String dateString){
    	boolean flag =false;
    	String yearString = "";
    	String monthString = "";
    	String dayString = "";
    	if(dateString.length()==8){
    		yearString = dateString.substring(0,4);
        	monthString = dateString.substring(4,6);
        	dayString = dateString.substring(6,8);
    	}else{
    		return true;
    	}
    	int yearInt = Integer.parseInt(yearString);
    	int monthInt = Integer.parseInt(monthString);
    	int dayInt = Integer.parseInt(dayString);
    	if(DateUtil.year(DateUtil.nowDate())!=yearInt){
    		return true;
    	}
    	if(monthInt>0&&monthInt<12){
    		switch (monthInt) {
			case 1:
				if(dayInt>31||dayInt<1)flag=true;
				break;
			case 2:
				if(isLeapYear(yearInt)){
					if(dayInt>29||dayInt<1)flag=true;
				}else{
					if(dayInt>28||dayInt<1)flag=true;
				}
				break;
			case 3:
				if(dayInt>31||dayInt<1)flag=true;
				break;
			case 4:
				if(dayInt>30||dayInt<1)flag=true;
				break;
			case 5:
				if(dayInt>31||dayInt<1)flag=true;
				break;
			case 6:
				if(dayInt>30||dayInt<1)flag=true;
				break;
			case 7:
				if(dayInt>31||dayInt<1)flag=true;
				break;
			case 8:
				if(dayInt>31||dayInt<1)flag=true;
				break;
			case 9:
				if(dayInt>30||dayInt<1)flag=true;
				break;
			case 10:
				if(dayInt>31||dayInt<1)flag=true;
				break;
			case 11:
				if(dayInt>30||dayInt<1)flag=true;
				break;
			case 12:
				if(dayInt>31||dayInt<1)flag=true;
				break;
				
			default:break;
			}
    	}else{
    		flag=true;
    	}
    	return flag;
    }
    /**
     * 获得上个月的时间
     * @return
     */
    public static Date getPreviousMonthEnd(){
    	Calendar lastDate = Calendar.getInstance();  
        lastDate.add(Calendar.MONTH,-1);//减一个月  
        lastDate.set(Calendar.DATE, 1);//把日期设置为当月第一天   
        lastDate.roll(Calendar.DATE, -1);//日期回滚一天，也就是本月最后一天  
        lastDate.set(Calendar.HOUR_OF_DAY, 23);
        lastDate.set(Calendar.MINUTE, 59);
        lastDate.set(Calendar.SECOND, 59);
        lastDate.set(Calendar.MILLISECOND, 0);
    	return lastDate.getTime();
    }
    public static Date getPreviousMonthFirst(){
    	Calendar lastDate = Calendar.getInstance();  
        lastDate.set(Calendar.DATE,1);//设为当前月的1号  
        lastDate.add(Calendar.MONTH,-1);//减一个月，变为下月的1号  
        lastDate.set(Calendar.HOUR_OF_DAY, 0);
        lastDate.set(Calendar.MINUTE, 0);
        lastDate.set(Calendar.SECOND, 0);
        lastDate.set(Calendar.MILLISECOND, 0);
        //lastDate.add(Calendar.DATE,-1);//减去一天，变为当月最后一天  
        //lastDate.set
        return lastDate.getTime();  
    }
    /**
     * 获得上个月的时间
     * @return
     */
    public static Date getDateMonthEnd(Date date){
    	Calendar calendar = Calendar.getInstance();  
    	calendar.setTime(date);
    	calendar.set(Calendar.DATE, 1);//把日期设置为当月第一天   
    	calendar.roll(Calendar.DATE, -1);//日期回滚一天，也就是本月最后一天  
    	calendar.set(Calendar.HOUR_OF_DAY, 23);
    	calendar.set(Calendar.MINUTE, 59);
    	calendar.set(Calendar.SECOND, 59);
    	calendar.set(Calendar.MILLISECOND, 0);
    	return calendar.getTime();
    }
    public static Date getDateMonthFirst(Date date){
    	Calendar calendar = Calendar.getInstance();  
    	calendar.setTime(date);
    	calendar.set(Calendar.DATE,1);//设为当前月的1号  
    	//calendar.add(Calendar.MONTH,-1);//减一个月，变为下月的1号  
    	calendar.set(Calendar.HOUR_OF_DAY, 0);
    	calendar.set(Calendar.MINUTE, 0);
    	calendar.set(Calendar.SECOND, 0);
    	calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();  
    }
    
    public static void main(String[] args){

    	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    	System.out.println("getPreviousMonthEnd:"+formatter.format(getDateMonthEnd(new Date())));
    	System.out.println("getPreviousMonthFirst:"+formatter.format(getDateMonthFirst(new Date())));
    	System.out.println(formatDateHour(new Date()));
    }
    
    
    /**
     * 以指定的格式来格式化日期
     *
     * @param date Date
     * @param format String
     * @return String
     */
    public static String formatDateByFormat(Date date,String format)
    {
        String result = "";
        if(date != null)
        {
            try
            {
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                result = sdf.format(date);
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
        return result;
    }
    
    
    /**
     * 指定时间格式转换为DATE
     * @param strDate
     * @param format
     * @return
     */
    public static Date parseFormatDate(String strDate,String format){
    	SimpleDateFormat sdf = new SimpleDateFormat(format);
    	try {
			return sdf.parse(strDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
    }
    
    
    //月份的第一天格式yyyy-MM-dd
    public static String getMonthBegin(String strdate,String format)
    {
    	
        java.util.Date date = parseFormatDate(strdate,format);
        return formatDateByFormat(date,"yyyy-MM") + "-01";
    }
    
    /**
     * 取得指定月份的最后一天
     *
     * @param strdate String
     * @return String
     */
    public static String getMonthEnd(String strdate,String format){
        java.util.Date date = parseFormatDate(strdate,format);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH,1);
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        return formatDate(calendar.getTime());
    }
    
    
    
}
